package com.yz.jdd.module.launch.presenter;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yz.jdd.R;
import com.yz.jdd.base.MyApplication;
import com.yz.jdd.base.entity.Response_Base;
import com.yz.jdd.base.event.Events;
import com.yz.jdd.base.event.RxBus;
import com.yz.jdd.base.utils.BaseConfigs;
import com.yz.jdd.base.utils.Constants;
import com.yz.jdd.base.utils.LogUtils;
import com.yz.jdd.base.utils.PreferencesUtils;
import com.yz.jdd.module.launch.model.AppVersion;
import com.yz.jdd.module.launch.model.H5Module;
import com.yz.jdd.module.launch.view.DeviceLoginView;
import com.yz.jdd.network.MySubscriber;
import com.yz.jdd.network.NetWorkRequset;
import com.yz.jdd.network.request.Requset_DeviceLogin;
import com.yz.jdd.network.response.Response_DeviceLogin;
import com.yz.jdd.network.response.Response_UserLogin;
import com.yz.jdd.webview.download.H5DownFileUtils;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by cc on 2017/5/15.
 */

public class DeviceLoginPresenter {

    // view 的引用
    private DeviceLoginView deviceLoginView;


    Requset_DeviceLogin requset_deviceLogin;

    Response_DeviceLogin response;

    public DeviceLoginPresenter(DeviceLoginView deviceLoginView) {
        super();
        this.deviceLoginView = deviceLoginView;

        requset_deviceLogin = new Requset_DeviceLogin();
    }

    public void unzip() {
        String version = deviceLoginView.getAppVersion();
        String localVersion = PreferencesUtils.getString(MyApplication.application, BaseConfigs.COMPARE_VERSION);
        if (TextUtils.isEmpty(version)) {
            version = "";
        }
        if (TextUtils.isEmpty(localVersion)) {
            localVersion = "";
        }
        PreferencesUtils.putString(MyApplication.application, BaseConfigs.COMPARE_VERSION, version);
        if (version.equals(localVersion)) {
            //相同
            File h5file = new File(H5DownFileUtils._UPZIP_FOLDERPATH);
            if (!h5file.exists()) {
                Map<String, String> h5Module = new HashMap<>();// N
                h5Module.put("base", MyApplication.application.getString(R.string.H5_base));
                h5Module.put("html", MyApplication.application.getString(R.string.H5_html));
                h5Module.put("css", MyApplication.application.getString(R.string.H5_css));
                h5Module.put("images", MyApplication.application.getString(R.string.H5_images));
                h5Module.put("js", MyApplication.application.getString(R.string.H5_js));
                h5Module.put("lib", MyApplication.application.getString(R.string.H5_lib));
                h5Module.put("vuepages", MyApplication.application.getString(R.string.H5_vuepages));
                Gson gson = new Gson();
                String jsonStr = gson.toJson(h5Module);
                PreferencesUtils.putString(
                        MyApplication.application, BaseConfigs.PREFS_STR_H5, jsonStr);

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        deviceLoginView.copyAssert();
                    }
                }).start();
            }
        } else {
            //不相同
            final File file = new File(H5DownFileUtils.DEFAULT_FOLDERPATH);
            Map<String, String> h5Module = new HashMap<>();// N
            h5Module.put("base", MyApplication.application.getString(R.string.H5_base));
            h5Module.put("html", MyApplication.application.getString(R.string.H5_html));
            h5Module.put("css", MyApplication.application.getString(R.string.H5_css));
            h5Module.put("images", MyApplication.application.getString(R.string.H5_images));
            h5Module.put("js", MyApplication.application.getString(R.string.H5_js));
            h5Module.put("lib", MyApplication.application.getString(R.string.H5_lib));
            h5Module.put("vuepages", MyApplication.application.getString(R.string.H5_vuepages));
            Gson gson = new Gson();
            String jsonStr = gson.toJson(h5Module);
            PreferencesUtils.putString(
                    MyApplication.application, BaseConfigs.PREFS_STR_H5, jsonStr);

            new Thread(new Runnable() {
                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    if (file.exists()) {
                        H5DownFileUtils.deleteFile(file);
                    }
                    deviceLoginView.copyAssert();
                }
            }).start();
        }
    }


    /**
     * 初始化设备登录请求
     */
    public void initRequest() {
        //读取app版本号 同时判断本地版本号 一致的话 如果文件不存在解压，不一致的话 删除，然后解压
        unzip();
        String firstTime = "true";// Y true 是否第一次设备登录
        String guid = deviceLoginView.getGUID();
        if (!TextUtils.isEmpty(guid)) {
            firstTime = "false";
        }
        requset_deviceLogin.setGuid(guid);
        requset_deviceLogin.setFirstTime(firstTime);

        String type = "21";// Y int app类型：1-pos，2-商家App 20-金多多 21-同福
        requset_deviceLogin.setType(type);

        String platform = "1";// Y int 平台：1-安卓；2-iOS
        requset_deviceLogin.setPlatform(platform);

        String appVersion = deviceLoginView.getAppVersion();// Y string 16
        // 当前设备app版本号
        requset_deviceLogin.setAppVersion(appVersion);

        // String hotfixVersion=deviceLoginView.getHotfixVersion();// N string
        // 16 当前设备热修复版本号
//        requset_deviceLogin.setHotfixVersion(BuildInfo.TINKER_ID);
        requset_deviceLogin.setHotfixVersion("");

        // 取历史位置信息，同事异步更新一下定位信息
        String lon = deviceLoginView.getLon();// N string 10 登录经度
        String lat = deviceLoginView.getLat();
        ;// N string 10 登录纬度

        String networkType = deviceLoginView.getNetWorkType();// N int 登录网络类型
        // 0-WIFI;1-移动网络
        if (!TextUtils.isEmpty(networkType)) {
            requset_deviceLogin.setNetworkType(networkType);
        }

        /**
         * H5Module 当前设备上有h5模块对应的版本号。 当设备中一个h5 module包都没有的时候可以不传；
         * 假如设备中有两个module包html、js， 对应的版本号为1.0、1.1，则该参数值为：
         "h5Module":[
         {"name":"base","version":"1.0"},
         {"name":"html","version":"1.1"}
         ]
         */

        Map<String, String> h5Module = new HashMap<>();// N
        String vs = PreferencesUtils.getString(MyApplication.application, BaseConfigs.PREFS_STR_H5, "");

        if (!TextUtils.isEmpty(vs)) {
            Gson gson = new Gson();
            h5Module = gson.fromJson(vs, new TypeToken<Map<String, String>>() {
            }.getType());
        }
        Gson gson = new Gson();

        requset_deviceLogin.setH5Module(h5Module);

        String imei = deviceLoginView.getIMEI();


        // N string 64 手机的IMEI或者pos的sn码。首次设备登录必传
        LogUtils.d("Imei =======" + imei);
        requset_deviceLogin.setImei(imei);

        // requset_deviceLogin.setImei("861299030093971");

        // 取当前信息，因为这个值也是异步返回,可以在设备登录接口不传
        String pushId = PreferencesUtils.getString(MyApplication.application, "pushId");// N string 64 push消息标识。首次设备登录必传
        requset_deviceLogin.setPushId(pushId);
        String sysVersion = deviceLoginView.getSysVersion();// N string 16
        // 安卓iOS系统版本号,比如4.4.4
        requset_deviceLogin.setSysVersion(sysVersion);

        String deviceModelStr = deviceLoginView.getDeviceModel();// N string 32
        // 手机型号
        requset_deviceLogin.setDeviceModel(deviceModelStr);

        requset_deviceLogin.setAliPushId(PreferencesUtils.getString(MyApplication.application, "alipushId"));

        requset_deviceLogin.setGetuiPushId(PreferencesUtils.getString(MyApplication.application, "getuiPushId"));

        requset_deviceLogin.setJigPushId(PreferencesUtils.getString(MyApplication.application, " jigPushId;"));

    }

    public void checkNetworkInfo() {
        //判断网络是否可用
        deviceLoginView.showLoadingNoCancelable("网络连接中");
        final long timeStap = System.currentTimeMillis();
        new Thread(new Runnable() {
            @Override
            public void run() {
                ConnectivityManager mConnectivityManager = (ConnectivityManager) MyApplication.application
                        .getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
                while (true) {
                    if (mNetworkInfo != null && mNetworkInfo.isAvailable()) {
                        //告诉主线程去请求
                        RxBus.getInstance().send(Events.EVENT_CONNECTION_SUCCESS, "");
                        break;
                    } else {
                        mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
                        if (10000 <= (System.currentTimeMillis() - timeStap)) {
                            //循环了10秒，告诉主线程
                            break;
                        }
                    }
                }
            }
        }).start();
    }

    /**
     * 执行设备登录
     */
    public void deviceLogin() {
        initRequest();

        try {

            NetWorkRequset.deviceLogin(
                    requset_deviceLogin,
                    new MySubscriber() {
                        @Override
                        public void onSuccess(Response_Base response_baseModel) {
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            response = (Response_DeviceLogin) response_baseModel
                                    .getResultObject();

                            if (response != null) {
                                Response_UserLogin user = response.getUser();
                                if (user != null) {

                                    PreferencesUtils.putString(
                                            MyApplication.application,
                                            BaseConfigs.PREF_SHOPNAME, user.getShopName());
                                    PreferencesUtils.putString(
                                            MyApplication.application,
                                            BaseConfigs.PREF_USERNAME, user.getUserName());

                                    PreferencesUtils.putBoolean(MyApplication.application, BaseConfigs
                                            .PREF_VERIFICATION_FLAG, user.isVerificationFlag());

                                    PreferencesUtils.putString(MyApplication.application, BaseConfigs
                                            .STRING_ROUTERCODE, user.getRouterCode());

                                    PreferencesUtils.putString(MyApplication.application, BaseConfigs
                                            .POS_SUPPLIERCODE, user.getSupplierCode());

                                    String shopId = user.getShopId();
                                    if (!TextUtils.isEmpty(shopId)) {
                                        PreferencesUtils.putString(
                                                MyApplication.application,
                                                BaseConfigs.PREF_SHOPID, shopId);
                                    }
                                    String regionName = user.getRegionName();
                                    PreferencesUtils.putString(MyApplication.application,
                                            BaseConfigs.STRING_REGIONNAME, regionName);


                                    String rc = user.getRc();
                                    if (!TextUtils.isEmpty(rc)) {
                                        PreferencesUtils.putString(
                                                MyApplication.application,
                                                BaseConfigs.STRING_ROUTE_CODE, rc);
                                    }
                                    Gson gson = new Gson();
                                    if (user.getHuabeiInfo() != null) {
                                        PreferencesUtils.putString(
                                                MyApplication.application,
                                                BaseConfigs.PREFS_STR_EXTINFO, gson.toJson(user.getHuabeiInfo()));
                                    } else {
                                        PreferencesUtils.putString(
                                                MyApplication.application,
                                                BaseConfigs.PREFS_STR_EXTINFO, "");
                                    }
                                    if (user.getMenuInfo() != null) {
                                        PreferencesUtils.putString(
                                                MyApplication.application,
                                                BaseConfigs.PREF_MENUINFO, gson.toJson(user.getMenuInfo()));
                                    }
                                }
                                String sessionId = response.getSessionId();
                                if (!TextUtils.isEmpty(sessionId)) {
                                    // 交接班、退出客户端清掉
                                    PreferencesUtils.putString(
                                            MyApplication.application,
                                            BaseConfigs.PREF_SESSIONID, sessionId);
                                }
                                String guidBack = response.getGuid();
                                if (!TextUtils.isEmpty(guidBack)) {

                                    PreferencesUtils.putString(
                                            MyApplication.application,
                                            BaseConfigs.STRING_GUID, guidBack);
                                }

                                List<H5Module> h5Module = response.getH5Module();
                                if (h5Module != null && h5Module.size() > 0) {
                                    PreferencesUtils.putBoolean(MyApplication.application,
                                            BaseConfigs.BOOLEAN_H5MODULE, false);
                                    deviceLoginView.downLoadH5Model(h5Module);

                                } else {
                                    PreferencesUtils.putBoolean(MyApplication.application,
                                            BaseConfigs.BOOLEAN_H5MODULE, true);
                                    showVersionUpdate();
                                }
//                                showVersionUpdate();
                            }
                        }

                        @Override
                        public void onNeedLogin(String msg) {
                            // 需要登录
                            deviceLoginView.dismissLoading();
                        }

                        @Override
                        public void onFail(Response_Base response_baseModel) {
                        }

                        @Override
                        public void onCompleted() {
                            deviceLoginView.dismissLoading();
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
            deviceLoginView.dismissLoading();
            deviceLoginView.showErrorDialog("系统异常");
        }

    }

    public void checkAutoLogin(String autoLogin) {
        if ("true".equals(autoLogin)) {
            deviceLoginView.startMainActivity();
            deviceLoginView.close();

        } else {
            deviceLoginView.startLoginActivity();
            deviceLoginView.close();
        }

    }

    public void showVersionUpdate() {
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (response != null) {
            AppVersion appVersion = response.getAppVersion();
            String autoLogin = response.getAutoLogin();
            PreferencesUtils.putString(MyApplication.application, Constants.PRE_IS_AUTO_LOGIN, autoLogin);
            deviceLoginView.setAppVersion(appVersion, autoLogin);

            if (appVersion != null) {

                final String url = appVersion.getAddress();
                if (!TextUtils.isEmpty(url)) {
                    deviceLoginView.showVersionUpdate(appVersion, url, autoLogin);
                }
            } else {
                checkAutoLogin(autoLogin);
            }
        }

    }
}
